package com.yunchao.feature.base.presentation.ext

import android.annotation.SuppressLint
import android.app.Activity
import android.app.DatePickerDialog
import android.app.Dialog
import android.content.DialogInterface
import androidx.annotation.DrawableRes
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import java.time.ZoneId
import com.xuexiang.xui.utils.WidgetUtils
import com.xuexiang.xui.widget.dialog.DialogLoader
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog
import com.xuexiang.xui.widget.dialog.strategy.InputInfo
import com.xuexiang.xui.widget.edittext.MultiLineEditText
import com.xuexiang.xui.widget.picker.widget.builder.TimePickerBuilder
import com.xuexiang.xui.widget.picker.widget.configure.TimePickerType
import com.yunchao.feature.base.R
import timber.log.Timber
import java.time.format.DateTimeFormatter
import java.util.Calendar


@SuppressLint("StaticFieldLeak")
private var mMiniLoadingDialog: MiniLoadingDialog? = null

fun Fragment.showLoadingDialog() {
    mMiniLoadingDialog?.show() ?: WidgetUtils.getMiniLoadingDialog(requireActivity())
        ?.let {
            mMiniLoadingDialog = it
            it.show()
        }
}

fun Fragment.showLoadingDialog(message: String) {
    mMiniLoadingDialog?.show() ?: WidgetUtils.getMiniLoadingDialog(requireActivity(), message)
        ?.let {
            mMiniLoadingDialog = it
            it.show()
        }
}
fun Activity.showLoadingDialog() {
    mMiniLoadingDialog?.show() ?: WidgetUtils.getMiniLoadingDialog(this)
        ?.let {
            mMiniLoadingDialog = it
            it.show()
        }
}

fun Activity.showLoadingDialog(message: String) {
    mMiniLoadingDialog?.show() ?: WidgetUtils.getMiniLoadingDialog(this, message)
        ?.let {
            mMiniLoadingDialog = it
            it.show()
        }
}

fun Fragment.hideLoadingDialog() {
    mMiniLoadingDialog?.dismiss()
    mMiniLoadingDialog = null
}

fun Activity.hideLoadingDialog() {
    mMiniLoadingDialog?.dismiss()
    mMiniLoadingDialog = null
}

fun Fragment.showTipDialog(
    @DrawableRes icon: Int = R.drawable.ic_success_img,
    title: String = this.getString(R.string.提示),
    submitText: String = this.getString(R.string.确定),
    content: String = this.getString(R.string.操作成功),
    block: (DialogInterface) -> Unit = {}
): Dialog = DialogLoader.getInstance()
    .showTipDialog(
        requireActivity(), icon, title, content, submitText
    ) { dialog, _ ->
        dialog?.let {
            block(it)
            it.dismiss()
        }
    }
fun Activity.showTipDialog(
    @DrawableRes icon: Int = R.drawable.ic_success_img,
    title: String = this.getString(R.string.提示),
    submitText: String = this.getString(R.string.确定),
    content: String = this.getString(R.string.操作成功),
    block: (DialogInterface) -> Unit = {}
): Dialog = DialogLoader.getInstance()
    .showTipDialog(
        this, icon, title, content, submitText
    ) { dialog, _ ->
        dialog?.let {
            block(it)
            it.dismiss()
        }
    }

fun Fragment.showConfirmDialog(
    title: String = this.getString(R.string.提示),
    content: String,
    submitText: String = this.getString(R.string.确定),
    cancelText: String = getString(R.string.取消),
    cancelCallback: (DialogInterface) -> Unit = {},
    block: (DialogInterface) -> Unit = {}
): Dialog = DialogLoader.getInstance()
    .showConfirmDialog(
        requireActivity(),
        title,
        content,
        submitText,
        { dialog, _ ->
            dialog?.let {
                block(it)
                it.dismiss()
            }
        },
        cancelText,
        { dialog, _ ->
            dialog?.let {
                cancelCallback(it)
                it.dismiss()
            }
        })

fun Activity.showInputDialog(
    b: Boolean = false,
    title: String,
    content: String,
    inputType: Int,
    defaultContent: String,
    block: (String?) -> Unit
) {
    DialogLoader.getInstance()
        .showInputDialog(
           this,
            R.drawable.ic_warning_img,
            title,
            content,
            if (b) InputInfo(inputType, defaultContent, defaultContent, true) else InputInfo(
                inputType,
                defaultContent
            ),
            { _, input -> Timber.i(input.toString()) },
            getString(R.string.确定),
            { dialog, _ ->
                val materialDialog = dialog as MaterialDialog
                val inputEditText = materialDialog.inputEditText
                block(inputEditText?.text.toString())
                dialog.dismiss()
            },
            getString(R.string.取消),
            null
        )
}

fun AppCompatActivity.showSingleChoiceDialog(
    title: String,
    items: List<String>,
    selectedIndex: Int,
    block: (Int) -> Unit
) {
    DialogLoader.getInstance()
        .showSingleChoiceDialog(
            this, title, items.toTypedArray(), selectedIndex, { dialog, which ->
                dialog.dismiss()
                block(which)
            }, getString(R.string.确定), getString(R.string.取消)
        )
}

fun Fragment.showSingleChoiceDialog(
    title: String,
    items: List<String>,
    selectedIndex: Int,
    block: (Int) -> Unit
) {
    DialogLoader.getInstance()
        .showSingleChoiceDialog(
            requireActivity(), title, items.toTypedArray(), selectedIndex, { dialog, which ->
                dialog.dismiss()
                block(which)
            }, getString(R.string.确定), getString(R.string.取消)
        )
}


fun Fragment.showMultiChoiceDialog(
    title: String,
    items: List<String>,
    selectedIndex: List<Int>,
    block: (List<Int>) -> Unit
) {
    MaterialDialog.Builder(requireActivity())
        .title(title)
        .items(items)
        .itemsCallbackMultiChoice(
            selectedIndex.toTypedArray()
        ) { dialog, which, _ ->
            dialog.dismiss()
            block(which.toList())
            true // allow selection
        }
        .positiveText(R.string.确定)
        .negativeText(R.string.取消)
        .show()
}


@SuppressLint("DefaultLocale", "PrivateResource")
fun Fragment.showDatePickerDialog(
    calendar: Calendar = Calendar.getInstance(),
    block: (date: String) -> Unit
) {
    DatePickerDialog(
        requireActivity(),
        com.xuexiang.xui.R.style.XUITheme_AlertDialog,
        { _, year, monthOfYear, dayOfMonth ->
            val formattedDate =
                String.format("%04d-%02d-%02d", year, monthOfYear + 1, dayOfMonth)
            block(formattedDate)
        },
        // 设置初始日期
        calendar.get(Calendar.YEAR),
        calendar.get(Calendar.MONTH),
        calendar.get(Calendar.DAY_OF_MONTH)
    ).show()
}

@SuppressLint("NewApi")
fun Fragment.showTimePickerDialog(
    calendar: Calendar = Calendar.getInstance(),
    block: (String) -> Unit
) {
    TimePickerBuilder(
        context
    ) { date, _ ->
        // 将 Date 转换为 LocalDateTime
        val localDateTime = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime()
        // 定义日期时间格式
        val dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
        // 格式化 LocalDateTime
        val formattedDateTime = localDateTime.format(dateTimeFormatter)
        block(formattedDateTime)
    }
        .setType(TimePickerType.ALL)
        .setTitleText("时间选择")
        .isDialog(false)
        .setOutSideCancelable(false)
        .setDate(calendar)
        .build().show()
}

@SuppressLint("NewApi")
fun Fragment.showBottomDatePickerDialog(
    calendar: Calendar = Calendar.getInstance(),
    block: (String) -> Unit
) {
    TimePickerBuilder(
        context
    ) { date, _ ->
        // 将 Date 转换为 LocalDateTime
        val localDateTime = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime()
        // 定义日期时间格式
        val dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
        // 格式化 LocalDateTime
        val formattedDateTime = localDateTime.format(dateTimeFormatter)
        block(formattedDateTime)
    }
        .setTitleText("日期选择")
        .isDialog(false)
        .setOutSideCancelable(false)
        .setDate(calendar)
        .build().show()
}

